package com.fbli.test.util;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;

import java.io.UnsupportedEncodingException;
import java.util.List;


public enum JsonUtil {

    INSTANCE;

    public String obj2json(Object obj) {
        try {
            return JSON.toJSONString(obj, SerializerFeature.WriteNonStringKeyAsString, SerializerFeature.WriteNullStringAsEmpty);
        } catch (Exception e) {
//            log.error("error[" + obj.getClass().getName() + "]", e);
        }
        return "{}";
    }

    public <T> T json2Obj(String json, Class<T> valueType) {
        try {
            return JSON.parseObject(json, valueType);
        } catch (Exception e) {
//            log.error("error", e);
        }
        return null;
    }

    public <T> T json2Obj(String json, TypeReference<T> valueType) {
        try {
            return JSON.parseObject(json, valueType);
        } catch (Exception e) {
//            log.error("error", e);
        }
        return null;
    }

    public <T> List<T> json2ObjArray(String json, Class<T> valueType) {
        try {
            return JSON.parseArray(json, valueType);
        } catch (Exception e) {
//            log.error("error", e);
        }
        return null;
    }

    public <T> T json2Obj(byte[] jsonByte, Class<T> valueType) {
        try {
            return JSON.parseObject(jsonByte, valueType);
        } catch (Exception e) {
            //                log.error(String.format("message[%s]", new String(jsonByte, "utf-8")), e);
        }
        return null;
    }

    public String obj2Json(Object obj, SerializeConfig config, SerializerFeature... SerializerFeature) {
        try {
            return JSON.toJSONString(obj, config, SerializerFeature);
        } catch (Exception e) {
//            log.error(String.format("message[%s]", obj.toString()), e);
        }
        return null;
    }

    public String obj2Json(Object obj, SerializerFeature... SerializerFeature) {
        try {
            return JSON.toJSONString(obj, SerializerFeature);
        } catch (Exception e) {
//            log.error(String.format("message[%s]", obj.toString()), e);
        }
        return null;
    }

}
